//
//  URLRouterManager.m
//  Router
//
//  Created by zhubangqian on 2018/2/23.
//  Copyright © 2018年 zhubangqian. All rights reserved.
//

#import "URLRouterManager.h"

@interface URLRouterManager()

@property(nonatomic, strong) NSMutableDictionary *routeRulesDictionary;

@end

@implementation URLRouterManager

+ (instancetype)shareInstance{
    static URLRouterManager *manager = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        manager = [[URLRouterManager alloc] init];
    });
    return manager;
}

- (instancetype)init{
    if (self = [super init]) {
        _routeRulesDictionary = [NSMutableDictionary dictionary];
    }
    return self;
}

- (void)execute:(NSString *)urlString{
    if (!urlString || urlString.length == 0) {
        return;
    }
    NSURL *url = [NSURL URLWithString:urlString];
    if (!url) {
        return;
    }
    NSString *path = [url path];
    
    NSArray *queryArr = [[url query] componentsSeparatedByString:@"&"];
    NSMutableDictionary *result = [NSMutableDictionary dictionary];
    
    if (queryArr) {
        for (NSString *str in queryArr) {
            NSArray *parts = [str componentsSeparatedByString:@"="];
            NSString *key = [parts[0] stringByRemovingPercentEncoding];
//            NSString *key = [parts[0] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
            if ([parts count] > 1)
            {
                id value = [parts[1] stringByRemovingPercentEncoding];
//                id value = [parts[1] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
                if (value && [value isKindOfClass:[NSString class]]) {
                    [result setObject:value forKey:key];
                }
            }
        }
    }
    
    [self execute:path params:result];
}

- (void)addRouterRule:(id<URLRouterRuleProtocol>)rule{
    if (!rule) {
        return;
    }
    if ([rule respondsToSelector:@selector(routerPath)]) {
        NSString *rulePath = [rule routerPath];
        
        [self.routeRulesDictionary setObject:rule forKey:rulePath];
    }
}

- (void)execute:(NSString *)rulePath params:(id)params{
    id<URLRouterRuleProtocol> rule = [self.routeRulesDictionary objectForKey:rulePath];
    [rule execute:params complete:nil];
}

- (void)execute:(NSString *)rulePath params:(id)params complete:(void(^)(id))completeBlock{
    id<URLRouterRuleProtocol> rule = [self.routeRulesDictionary objectForKey:rulePath];
    [rule execute:params complete:completeBlock];
}

@end
